package com.lin.manager.secure.filter;

import com.lin.manager.secure.ex.CustomAuthenticationException;
import com.lin.manager.secure.service.code.CodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @作者: 林江
 * @创建时间: 2024/3/16
 * @功能: 验证码过滤器
 */
@Slf4j
public class CodeFilter extends OncePerRequestFilter {
    private final static String CODE = "code";
    private AuthenticationFailureHandler failureHandler;
    private CodeService codeService;

    public void setFailureHandler(AuthenticationFailureHandler failureHandler) {
        this.failureHandler = failureHandler;
    }

    public void setCodeService(CodeService codeService) {
        this.codeService = codeService;
    }

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER =
            new AntPathRequestMatcher("/login");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!DEFAULT_ANT_PATH_REQUEST_MATCHER.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取验证码
        String uriCode = request.getParameter(CODE);
        log.info("验证码code：【{}】", uriCode);
        if (StringUtils.isEmpty(uriCode)) {
            CustomAuthenticationException exception = new CustomAuthenticationException("验证码不能为空");
            failureHandler.onAuthenticationFailure(request, response, exception);
            return;
        }

        // 校验验证码
        if (!codeService.verifyCode(uriCode)) {
            CustomAuthenticationException exception = new CustomAuthenticationException("验证码错误");
            failureHandler.onAuthenticationFailure(request, response, exception);
            return;
        }

        // 删除验证码
        codeService.removeCode(uriCode);

        filterChain.doFilter(request, response);
    }

}
